import grails.converters.XML

class EventController {

  def queryService
  def index = { redirect(action: myEvents, params: params) }

  // the save and update actions only accept POST requests
  static allowedMethods = [save: 'POST', update: 'POST']

  def myEvents = {
    // return a maximum number of events
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    def ownerVolunteer = Volunteer.get(session.volunteer.id)
    //def myEventList = Event.findAllByOwner(ownerVolunteer, params)
    def myEventList = queryService.myEvents(ownerVolunteer, params.max)
    [eventInstanceList: myEventList, eventInstanceTotal: queryService.eventCount()]
  }

  def futureEvents = {
    // return a maximum number of events
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //def eventInstanceList = Event.findAll("From Event as e where e.endDate > :today", [today: new Date()])
    def eventInstanceList = queryService.futureEvents(params.max)
    withFormat {
      html {
        return [eventInstanceList: eventInstanceList, eventInstanceTotal: queryService.eventCount()]
      }
      xml {
        render eventInstanceList as XML
      }
    }
  }

  def show = {
    def eventInstance = Event.get(params.id)

    if (!eventInstance) {
      withFormat {
        html {
          flash.message = "Event not found with id ${params.id}"
          redirect(action: myEvents)
        }
        xml {
          def error = ['error': "Event not found with id ${params.id}."]
          render error as XML
        }
      }
    }
    else {
      withFormat {
        html {
          def unfilledPositions = eventInstance.positions
          return [eventInstance: eventInstance, unfilledPositions: unfilledPositions]
        }
        xml {
          render eventInstance as XML
        }
      }
    }
  }

  def positionTable = {
    def eventInstance = Event.get(params.id)

    if (!eventInstance) {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: myEvents)
    }
    else {
      def unfilledPositions = eventInstance.positions
      render template: '/common/positionTable', model: [eventInstance: eventInstance, unfilledPositions: unfilledPositions]
    }
  }

  def delete = {
      def eventInstance = Event.get(params.id)
      //def ownerVolunteer = Volunteer.get(session.volunteer.id)
      if (eventInstance) {
        if (session.volunteer.id != eventInstance.owner.id) {
          flash.message = "You can only delete your own events"
          redirect(action: myEvents)
          return
        }

        try {
          eventInstance.delete(flush: true)
          flash.message = "Event ${params.id} deleted"
          redirect(action: myEvents)
        }
        catch (org.springframework.dao.DataIntegrityViolationException e) {
          flash.message = "Event ${params.id} could not be deleted"
          redirect(action: show, id: params.id)
        }
      }
      else {
        flash.message = "Event not found with id ${params.id}"
        redirect(action: myEvents)
      }
    }

    def edit = {
      def eventInstance = Event.get(params.id)

      if (!eventInstance) {
        flash.message = "Event not found with id ${params.id}"
        redirect(action: myEvents)
      }
      else {
        if (session.volunteer.id != eventInstance.owner.id) {
          flash.message = "You can only edit your own events"
          redirect(action: myEvents)
          return
        }

        return [eventInstance: eventInstance]
      }
    }

    def update = {
      def eventInstance = Event.get(params.id)

      def ownerVolunteer = Volunteer.get(session.volunteer.id)
      if (eventInstance) {
        if (session.volunteer.id != eventInstance.owner.id) {
          flash.message = "You can only update your own events"
          redirect(action: myEvents)
          return
        }
        eventInstance.properties = params
        eventInstance.owner = ownerVolunteer
        if (params.version) {
          def version = params.version.toLong()
          if (eventInstance.version > version) {
            // this should never happen since only the owner can update
            eventInstance.errors.rejectValue("version", "event.optimistic.locking.failure", "Another user has updated this Event while you were editing.")
            render(view: 'edit', model: [eventInstance: eventInstance])
            return
          }
        }
        eventInstance.properties = params
        if (!eventInstance.hasErrors() && eventInstance.save()) {
          flash.message = "Event ${params.id} updated"
          redirect(action: show, id: eventInstance.id)
        }
        else {
          render(view: 'edit', model: [eventInstance: eventInstance])
        }
      }
      else {
        flash.message = "Event not found with id ${params.id}"
        redirect(action: edit, id: params.id)
      }
    }

    def create = {
      def eventInstance = new Event()
      eventInstance.properties = params
      eventInstance.owner = session.volunteer
      return ['eventInstance': eventInstance]
    }

    def save = {
      def eventInstance = new Event(params)

      def ownerVolunteer = Volunteer.get(session.volunteer.id)
      // set the owner to the current session volunteer
      eventInstance.owner = ownerVolunteer

      if (!eventInstance.hasErrors() && eventInstance.save()) {
        flash.message = "Event ${eventInstance.name} created"
        redirect(controller: 'eventPosition', action: 'create', id: eventInstance.id)
      }
      else {
        render(view: 'create', model: [eventInstance: eventInstance])
      }
    }

    def createPosition = {
      redirect(controller: 'eventPosition', action: 'create', id: params.id)
    }
}